package com.share.device.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.device.domain.Region;
import com.share.device.mapper.RegionMapper;
import com.share.device.service.IRegionService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService
{

    //根据上级code获取下级数据数据列表
    @Override
    public List<Region> treeSelect(String parentCode) {

        //封装条件
        LambdaQueryWrapper<Region> wrapper=new LambdaQueryWrapper();
        wrapper.eq(Region::getParentCode,parentCode);
        List<Region> regionList = baseMapper.selectList(wrapper);

        //判断下一层数据是否存在，如果有hasChildren=true,否则false
        //把查询出来的列表遍历，得到每个region
        if(!CollectionUtils.isEmpty(regionList)){
            regionList.forEach(region -> {
                LambdaQueryWrapper<Region> wrapper1=new LambdaQueryWrapper();
                //查询每个regiou对象是否有下一层数据parent_code=?
                wrapper1.eq(Region::getParentCode,region.getCode());
                Long count = baseMapper.selectCount(wrapper1);
                if (count > 0 ) {
                    region.setHasChildren(true);
                }else{
                    region.setHasChildren(false);
                }
            });
        }
        return regionList;
    }

    //根据编号返回对应的名称
    @Override
    public String getNameByCode(String code) {
        if (StringUtils.isEmpty(code)) {
            return "";
        }
        Region region = baseMapper.selectOne(new LambdaQueryWrapper<Region>().eq(Region::getCode,code).select(Region::getName));
        if(null != region) {
            return region.getName();
        }
        return "";
    }
}
